//
//  GroupChatViewController.m
//  IMChat
//
//  Created by Admin on 2021/7/4.
//  Copyright © 2021年 TeamOne. All rights reserved.
//

#import "GroupChatViewController.h"
#import "WWXUser.h"
#import "WWXLinklist.h"

@interface GroupChatViewController () <UITableViewDataSource, UITableViewDelegate>
//搜索框
@property (weak, nonatomic) IBOutlet UITextField *searchTV;
//已选框
@property (weak, nonatomic) IBOutlet UIScrollView *selectedSV;
//用户列表
@property (weak, nonatomic) IBOutlet UITableView *friendTV;

//通讯录用户信息
@property (nonatomic, strong) NSArray *userArray;
//选择群聊的用户信息
@property (nonatomic, strong) WWXLinkList *groupList;

//好友信息对象数组
@property (strong, nonatomic) NSMutableArray<FriendInfoModel *> *friendModelList;

@end

@implementation GroupChatViewController

//接入数据数据
- (NSArray *)userArray
{
    if (!_userArray) {
        WWXUser *user0 = [WWXUser userWithName:@"温文曦" icon:@"touxiang5" userId:@"13265006396"];
        WWXUser *user1 = [WWXUser userWithName:@"吴于伶" icon:@"touxiang1" userId:@"13211111111"];
        WWXUser *user2 = [WWXUser userWithName:@"潘登永" icon:@"touxiang2" userId:@"13222222222"];
        WWXUser *user3 = [WWXUser userWithName:@"程伟杰" icon:@"touxiang3" userId:@"13233333333"];
        WWXUser *user4 = [WWXUser userWithName:@"李老师" icon:@"touxiang4" userId:@"13244444444"];
        _userArray = @[user0,user1,user2,user3,user4];
    }
    return _userArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置sv
    self.selectedSV.contentSize = CGSizeMake(400, 40);
    //设置tv
    self.friendTV.dataSource = self;
    self.friendTV.delegate = self;
    //初始化LinkList
    self.groupList = [WWXLinkList initLinkList];
    
    /** 获得全局变量. */
    AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    _friendModelList = myDelegate.friendModelList;
    
}

#pragma mark- UITableViewDataSourse
//组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_friendModelList count];
}
//设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取出数据
    //WWXUser *user = self.userArray[indexPath.row];
    FriendInfoModel *friendModel = _friendModelList[indexPath.row];
    //创建格子
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    //设置数据
    cell.textLabel.text = friendModel.friendName;
    cell.imageView.image = [UIImage imageNamed:@"touxiang1"];
    return cell;
}

#pragma mark - UITableViewDelegate
//选择事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //获取路径
    NSIndexPath *idPath = [_friendTV indexPathForSelectedRow];
    //拿到cell
    UITableViewCell *cell = [_friendTV cellForRowAtIndexPath:idPath];
    //拿到元素
    //WWXUser *user = self.userArray[indexPath.row];
    FriendInfoModel *friendModel = _friendModelList[indexPath.row];
    //判断是否选中
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        //从SV中移除头像
        [self removeIcon:friendModel];
        //取消选中
        cell.accessoryType = UITableViewCellAccessoryNone;
    }else{
        //插入头像到SV
        [self insertIcon:friendModel];
        //设置选中
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}
//插入Icon
-(void)insertIcon:(FriendInfoModel*) friend{
    //得到控件索引
    NSInteger x = self.selectedSV.subviews.count-2;
    //创建IV
    UIImageView *headIcon = [[UIImageView alloc]init];
    //设置位置
    headIcon.frame = CGRectMake(40*x, 2, 36, 36);
    //设置图片
    headIcon.image = [UIImage imageNamed:@"touxiang1"];
    //添加子控件
    [self.selectedSV addSubview:headIcon];
    //插入数据到链表
    [self.groupList insertData:friend];
}
//移除Icon
-(void)removeIcon:(FriendInfoModel*) friend{
    //遍历子控件
    for(UIImageView *headIcon in self.selectedSV.subviews){
        //找到该元素
        if (headIcon.image == [UIImage imageNamed:@"touxiang1"]) {
            //从父类移除
            [headIcon removeFromSuperview];
            //排序
            for(int i = [self.groupList indexOfData:friend];i<self.selectedSV.subviews.count-2;i++){
                UIImageView *Icon= self.selectedSV.subviews[i+2];
                Icon.frame = CGRectMake(40*i, 2, 36, 36);
            }
            //从链表中移除
            [self.groupList removeData:[self.groupList indexOfData:friend]];
            break;
        }
    }
}
//提交
- (IBAction)commitUser:(id)sender {
    //转数组
    NSMutableArray *groupArr = [self.groupList toMutableArray];
//    //遍历
//    for (WWXUser *user in groupArr){
//        //打印
//        NSLog(@"%@",user.userId);
//    }
    /** 获得全局变量. */
    AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    NSMutableArray *groupMemberList = [[NSMutableArray alloc]initWithCapacity:10];
    //先放Owner
    [groupMemberList addObject:myDelegate.userId];
    for(FriendInfoModel *friendModel in groupArr){
        [groupMemberList addObject:friendModel.friendId];
    }
    
    RCGroupNotificationMessage *groupMsg = [[RCGroupNotificationMessage alloc]init];
    groupMsg.operatorUserId = myDelegate.user.userId;
    groupMsg.operation = @"Create";
    groupMsg.data = @{@"operatorNickname":myDelegate.user.userName,};
    groupMsg.message = @"创建群组";
    NSLog(@"data:%@",groupMsg.data);
    
    [TOAFHttpUtils addGroupInfo:groupMemberList block:^(NSString * _Nonnull result) {
        if([result isEqualToString:@"error-1001"]){
            [self alertTool:@"创建过程遇到了错误，请重新创建～"];
        }else if([result isEqualToString:@"error-1000"]){
            [self alertTool:@"创建过程遇到了错误，请重新创建～"];
        }else{
            NSLog(@"已添加，获得群组号：%@",result);
            [TOAFHttpUtils createGroup:groupMemberList
              groupId:result
              withBolck:^(NSString * _Nonnull result) {
                  NSLog(@"群组号：%@",result);
                  if([result isEqualToString:@"error"]){
                      [self alertTool:@"创建过程遇到了错误，请重新创建～"];
                  }else{
                      NSLog(@"发送信息~");
                      [self.navigationController popViewControllerAnimated:true];

                      [self alertTool:@"创建成功！"];
                      
                      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                          
                          [[RCIM sharedRCIM]sendMessage:ConversationType_GROUP
                                               targetId:result
                                                content:groupMsg
                                            pushContent:nil pushData:nil
                                                success:^(long messageId) {
                                                    NSLog(@"成功！");
                                                } error:^(RCErrorCode nErrorCode, long messageId) {
                                                    NSLog(@"失败%ld",(long)nErrorCode);
                                                }];
                          //[TOAFHttpUtils sendGroupMessage:result content:groupMsg];
                      });   
                      
                  }
              }];
        }
    }];
    
}
//清空
- (IBAction)clearUser:(id)sender {
    while (self.selectedSV.subviews.count>2) {
        [self.selectedSV.subviews[2] removeFromSuperview];
    }
    [self.groupList clear];
    for (int i = 0; i<[_friendModelList count]; i++) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
    UITableViewCell *cell = [_friendTV cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
    }
}

// 弹窗工具
- (void)alertTool:(NSString *)message{
    //先创建一个弹窗控制器 然后里面有title和message来提示需要的东西
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    //添加一个弹窗的action 活动可以是取消 可以是确认
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:NO completion:nil];
}

@end
